// stock/goods_update/goods_update.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tableName: '商品定义',
    fieldList: [
      {field_id: 'goods_id', label: '商品编码',type: 'text',is_null: false}
      ,{field_id: 'goods_name', label: '商品名称',type: 'text',is_null: false}
      ,{field_id: 'goods_type', label: '商品类别',type: 'picklist',is_null: false, option: [],optionId: 'id',optionName: 'label'}
      ,{field_id: 'goods_model', label: '规格型号',type: 'picklist',is_null: true,optionId: 'row_id',optionName: 'goods_model_name', option: []}
      ,{field_id: 'goods_brand', label: '品牌',type: 'picklist',is_null: true,optionId: 'row_id',optionName: 'goods_brand_name', option: []}
      ,{field_id: 'goods_place', label: '产地',type: 'picklist',is_null: true, option: [],optionId: 'id',optionName: 'label'}
      ,{field_id: 'goods_unit', label: '单位',type: 'picklist',is_null: true,optionId: 'row_id',optionName: 'goods_unit_name', option: []}
    ],
    defData:{},
    formData:{
      goods_id: '',
      goods_name:'',
      goods_type: '',
      goods_model: '',
      goods_brand: '',
      goods_place:'',
      goods_unit: '',
      is_used: true
    },

    validFlag: false,             // 验证标识
    validObj: {},                 // 验证表单项


  },

  // 记录验证表单项
  validIpt(e) {
    let { validObj, } = this.data
    this.data.validObj = {
      ...validObj,
      ...e.detail,
    };
  },
  //启用标识
  toggleUsed(e) {
    let detail = e.detail,
      {formData} = this.data;
    formData.is_used = detail;
    this.setData({formData});
  },

  //布局中字段修改
  bindChange(e){
    let detail = e.detail,
      field = detail.field,
      id = field.field_id || field.fieldName,
      type = field.type,
      val = detail.val,
      formData = this.data.formData;
    formData[id] = val;
  },

  //绑定提交
  bindSubmit(e){
    let type = e.currentTarget.dataset.type;

    // 开启验证
    this.data.validObj = {};
    this.setData({
      validFlag: !this.data.validFlag,
    });
    let {validObj} = this.data;
    wx.showLoading({mask: true});
    this.validForm(validObj).then(valid => {
      if(valid) { // 表单验证通过
        let {formData,tableName} = this.data;
        console.log('表单验证通过');
        let post = {
            "table":{
              "table_id":"goods",
              "entitys":[
                {"entity": formData,"details":[]}
                ]}};
        wx.$post(3,'DynamicUpdate/dynamic_update_v3',post).then(res=>{
          if (res.errcode !=0)return;
          wx.$toast('保存成功！');
          this.refreshList(formData.row_id,this.data.editIndex)

          //关闭
          if (type === 'close'){
            wx.navigateBack({ //跳转到前一个页面
              delta:1,//前一个页面
            });
          }
          //清空
          if (type === 'clear'){
            formData = {is_used: true};
            tableName = '新增商品';
          }
          //复制
          if (type === 'copy'){
            formData.row_id = 0;
            tableName = '复制商品';
          }
          this.setData({
            formData,
            tableName
          });
        });

      } else {  // 表单验证不通过
        console.log('表单验证不通过');
        wx.$toast('必填项不能为空！')
      }
    })
  },

  //刷新列表
  refreshList(id,index){
    const pages = getCurrentPages();//获取页面栈
    const beforePage = pages[pages.length - 2];  //前一个页面
    beforePage.refreshData(id,index);
  },

  //验证数据
  validForm(validObj){
    return new Promise((resolve, reject) => {
      let valid = Object.values(validObj).includes(false) ? false : true;
      resolve(valid)
    })
  },

  //循环遍历数据
  eachData(arr,oid,name){
    let list = [];
    wx.$each(arr,(i,item)=>{
      list.push({
        id: item[oid],
        label: item[name],
      });
      if (item.children) {
        list = [...list,...this.eachData(item.children,oid,name)]
      }
    });
    return list;
  },

  //获取下拉选项
  getOptionsList(arg){
    let [key,v,url,post,iseach,parse] = arg;
    return new Promise((resolve,reject) => {
      wx.$post(v, url, post).then(res=>{
        if (res.errcode != 0){
          reject();
          return;
        }
        let data = res.data.row || [],
          list = data;
        if (iseach){
          list = this.eachData(data,'row_id',parse);
        }
        resolve({[key]: list});
      });
    });
  },

  ready(options){
    let {rowid,status,edit_index} = options,
      tableName = '新增商品',
      obj = {};
    if (status === 'edit'){
      tableName = '编辑商品'
    }
    if (status === 'copy'){
      tableName = '复制商品'
    }
    obj = {tableName};
    if (edit_index !== undefined)obj.editIndex = edit_index;
    this.setData(obj);

    let parmaArr = [
      ['goods_type',1,'Stock/query_goods_type_level',{"row_id": 0},true,'goods_type_name'],  //类别
      ['goods_model',3,'DynamicQuery/query_dynamic_v1',{"oby": "goods_model.row_id desc","table_id": "goods_model","page":1,"limit":0}],  //型号
      ['goods_brand',3,'DynamicQuery/query_dynamic_v1',{"oby": "goods_brand.row_id desc","table_id": "goods_brand","page":1,"limit":0}],  //品牌
      ['goods_place',1,'Stock/query_goods_place_level',{"row_id": 0},true,'place_name'],  //产地
      ['goods_unit',3,'DynamicQuery/query_dynamic_v1',{"oby": "goods_unit.row_id desc","table_id": "goods_unit","page":1,"limit":0}],  //单位
    ],
      pmArr = [];
    wx.$each(parmaArr,(i,item)=>{
      pmArr.push(this.getOptionsList(item));
    });
    Promise.all(pmArr.map(p => p.catch(err => ''))).then(res=>{
      let resObj = {};
      wx.$each(res,(i,item)=>{
        resObj = {...resObj,...item}
      });
      let fieldList = this.data.fieldList;
      wx.$each(fieldList,(i,item)=>{
        if (resObj[item.field_id]){
          item.optionList = resObj[item.field_id];
        }
      });

      this.setData({
        fieldList,
      });

      if (rowid){
        this.getData(rowid).then(row=>{
          let data= row[0] && row[0].entity[0],
            {formData} = this.data;
          wx.$each(formData,(key,val)=>{
            formData[key] = data[key];
          });
          if (status === 'copy'){
            formData.row_id = 0;
          } else {
            formData.row_id = data.row_id;
            formData.is_used = data.is_used;
          }
          this.setData({formData})

        })
      }
    })
  },

  getData(rid){
    return new Promise(resolve => {
      wx.$post(3,'DynamicQuery/query_dynamic_v2',{table_id: "goods", row_id: rid}).then(res=>{
        if (res.errcode != 0)return;
        let data = res.data.row || [];
        resolve(data);
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.$setBarTitle();
    this.ready(options);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
